package com.tomato.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tomato.dto.TodoSettingDTO;
import com.tomato.dto.TodoSettingSyncDTO;
import com.tomato.entity.TodoSetting;
import com.tomato.mapper.BatchMapper;
import com.tomato.mapper.TodoSettingMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class TodoSettingServiceImpl implements TodoSettingService {
    private final TodoSettingMapper todoSettingMapper;
    private final BatchMapper batchMapper;

    public TodoSettingServiceImpl(TodoSettingMapper todoSettingMapper,
                                  BatchMapper batchMapper) {
        this.todoSettingMapper = todoSettingMapper;
        this.batchMapper = batchMapper;
    }

    @Override
    public TodoSetting createSetting(Long userId, TodoSettingDTO settingDTO) {
        log.debug("Creating new todo setting for user: {}", userId);
        TodoSetting setting = new TodoSetting();
        BeanUtils.copyProperties(settingDTO, setting);
        setting.setUserId(userId);
        setting.setCreatedAt(LocalDateTime.now());
        setting.setUpdatedAt(LocalDateTime.now());

        todoSettingMapper.insert(setting);
        log.info("New todo setting created: {}", setting.getId());
        return setting;
    }

    @Override
    public List<TodoSetting> getUserSettings(Long userId) {
        log.debug("Fetching todo settings for user: {}", userId);
        return todoSettingMapper.selectByUserId(userId);
    }

    @Transactional
    @Override
    public void syncSettings(Long userId, List<TodoSettingSyncDTO> syncDTOs) {
        log.debug("Syncing todo settings for user: {}", userId);
        LocalDateTime uploadedAt = LocalDateTime.now();

        // 1. 删除用户所有现有设定
        todoSettingMapper.deleteByUserId(userId);

        // 2. 转换并插入新设定
        if (!syncDTOs.isEmpty()) {
            List<TodoSetting> settings = syncDTOs.stream()
                    .map(dto -> dto.toEntity(userId, uploadedAt))
                    .toList();

            batchMapper.batchInsertSettings(settings);
            log.info("Synced {} settings for user: {}, uploaded at: {}",
                    settings.size(), userId, uploadedAt);
        }
    }
}